<template>
  <div class="chat-container">
    <com-tab-bar :title="title"/>
    <div>
      <p v-if="favorCount">关注数: {{favorCount}}</p>
      <van-row v-if="base64Str">
        <van-image
          :src="base64Str"
          fit="scale-down"
        />
      </van-row>
      <van-row>
        <van-button
          type="primary"
          size="small"
          round
          @click="getMyEWM">
          领取我的二维码
        </van-button>
        <van-button
          type="warning"
          size="small"
          round
          @click="downMyEWM">
          下载我的二维码
        </van-button>
      </van-row>
    </div>
  </div>
</template>

<script>
import comTabBar from '../../components/comTapBar'
import { mapState } from 'vuex'

export default {
  data() {
    return {
      title: '联系客服',
      base64Str: '',
      EWMBase64String: '',
    }
  },
  components: {
    comTabBar
  },
  computed: {
    ...mapState({
      favorCount: (state)=>{
        let _num = state.favorCount
        if (_num > 1000) {
          _num = (_num/1000).toFixed(1) + 'k'
        }
        return _num
      }
    }),
  },
  methods: {
    // 领取 按钮事件
    getMyEWM() {
      // 发送请求获取服务器返回的图片base64字符串
      // TODO
      setTimeout(()=>{
        this.base64Str = this.EWMBase64String
      }, 2000)
    },
    // 下载 按钮事件
    downMyEWM() {
      const blobImageFile = this.base64ToBlob(this.base64Str,'二维码')
      this.dowloadBlobImageFile(blobImageFile)
    },
    // 下载BlobFile图片
    dowloadBlobImageFile(blobRes) {
      if (!blobRes) { this.$toast('资源不存在'); return; }
      try {
        const fileFullName = (blobRes.name + '.'+ blobRes.type.split('/')[1]) || 'defualt.png'
        const tempDom = document.createElement("a")
        tempDom.href = URL.createObjectURL(blobRes)
        tempDom.download = fileFullName
        tempDom.click()
        URL.revokeObjectURL(tempDom.href)
        tempDom.remove()
        this.$toast('图片成功')
      }catch(err) { this.$toast('图片下载异常'+err) }
    },
    // base64转BlobFile
    base64ToBlob(dataurl, filename="default") {
      if (!dataurl) { this.$toast('请传入base64 image 字符串'); return;}
      try{
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while(n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], filename, {type:mime})
      }catch(err) { this.$toast('base64ToBlob失败') }
    }
  }
}
</script>

<style lang="scss">

</style>
